package com.lin.linchatgpt.service.impl;

import com.lin.linchatgpt.entity.Message;
import com.lin.linchatgpt.entity.table.MessageTableDef;
import com.lin.linchatgpt.entity.vo.ChatMessageVo;
import com.lin.linchatgpt.exception.LinException;
import com.lin.linchatgpt.mapper.MessageMapper;
import com.lin.linchatgpt.service.MessageService;
import com.lin.linchatgpt.utils.NanoMillisUtils;
import com.lin.linchatgpt.utils.ResultCode;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/6/13 19:47
 * @Description
 */
@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Override
    public List<ChatMessageVo> getMessages(String subjectId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(MessageTableDef.MESSAGE.SUBJECT_ID.eq(subjectId));
        // 按时间排序
        queryWrapper.orderBy(MessageTableDef.MESSAGE.RECORD_TIME.asc());
        List<Message> list = this.list(queryWrapper);
        // 转换为ChatMessageVo
        ArrayList<ChatMessageVo> chatMessageVos = new ArrayList<>();

        for (int i = 0; i < list.size(); ) {
            Message question = list.get(i);
            Message answer = list.get(i + 1);
            ChatMessageVo chatMessageVo = new ChatMessageVo(question, answer);
            chatMessageVos.add(chatMessageVo);
            i += 2;
        }

        return chatMessageVos;
    }

    @Override
    public List<Message> modifyMessage(Message message) {
        // 查询出要修改的记录的创建时间
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select(MessageTableDef.MESSAGE.RECORD_TIME);
        wrapper.where(MessageTableDef.MESSAGE.ID.eq(message.getId()));
        Message SourceMessage = this.getOne(wrapper);

        // 查询出所有记录
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(MessageTableDef.MESSAGE.SUBJECT_ID.eq(message.getSubjectId()));
        queryWrapper.orderBy(MessageTableDef.MESSAGE.RECORD_TIME.asc());
        List<Message> messages = this.list(queryWrapper);
        // 当有历史记录时，才修改数据库
        if (messages.size() > 0) {
            // 定位到要修改的记录
            // 遍历messages时间找到大于要修改的记录的所有记录，包括该记录
            List<Message> deleteMessages = messages.stream()
                    .filter(x -> x.getRecordTime() > SourceMessage.getRecordTime())
                    .collect(Collectors.toList());
            // 删除大于要修改的记录的所有记录
            this.removeByIds(deleteMessages.stream().map(Message::getId).collect(Collectors.toList()));
            // 删除messages中的大于要修改的记录的所有记录
            messages.removeAll(deleteMessages);
        }
        // 添加修改后的记录
        message.setRecordTime(NanoMillisUtils.getMillisTime());

        // 删除原来的记录
        messages.remove(messages.size() - 1);
        // 添加修改后的记录
        messages.add(message);

        return messages;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMessage(Message questionMessage, Message answerMessage, int type) {
        switch (type) {
            case 0:
            case 1:
                this.save(questionMessage);
                this.save(answerMessage);
                break;
            case 2:
                this.updateById(questionMessage);
                this.save(answerMessage);
                break;
            default:
                throw new LinException(ResultCode.ERROR, "未知的消息类型");
        }
    }
}
